package org.ak47.spring.boot.grpc.autoconfigure;


import io.grpc.ServerInterceptor;
import lombok.Getter;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.lang.NonNull;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 * <p> grpc server 全局拦截器注册表 </p>
 *
 * @author hexiaohong
 */
@Getter
public class GlobalServerInterceptorRegistry implements ApplicationContextAware
{
    private ApplicationContext applicationContext;

    /**
     * 注册表
     */
    private final List<ServerInterceptor> serverInterceptors = new ArrayList<>();

    @PostConstruct
    public void init()
    {
        Map<String, GlobalServerInterceptorConfigurerAdapter> map = applicationContext.getBeansOfType(
            GlobalServerInterceptorConfigurerAdapter.class);
        for (GlobalServerInterceptorConfigurerAdapter adapter : map.values())
        {
            adapter.addServerInterceptors(this);
        }
    }

    public GlobalServerInterceptorRegistry addServerInterceptors(ServerInterceptor serverInterceptor)
    {
        this.serverInterceptors.add(serverInterceptor);
        return this;
    }

    @Override
    public void setApplicationContext(@NonNull ApplicationContext applicationContext)
        throws BeansException
    {
        this.applicationContext = applicationContext;
    }
}
